<template>
  <div class="sys-section-bg">
    <div style="height:32px;"></div>
    <el-row :gutter="20" class="sys-stat-row">
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#409EFF" size="22"><i-ep-warning /></el-icon>
            <div class="stat-info">
              <div class="stat-title">日志总数</div>
              <div class="stat-value">{{ Array.isArray(logs) ? logs.length : 0 }}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#67C23A" size="22"><i-ep-warning /></el-icon>
            <div class="stat-info">
              <div class="stat-title">今日日志</div>
              <div class="stat-value">{{todayLogsCount}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#E6A23C" size="22"><i-ep-warning /></el-icon>
            <div class="stat-info">
              <div class="stat-title">本周日志</div>
              <div class="stat-value">{{weekLogsCount}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card shadow="hover" class="sys-stat-card">
          <div class="stat-card">
            <el-icon color="#F56C6C" size="22"><i-ep-warning /></el-icon>
            <div class="stat-info">
              <div class="stat-title">本月日志</div>
              <div class="stat-value">{{monthLogsCount}}</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <el-divider content-position="left">日志列表</el-divider>
    <div class="page-title">
      <el-icon><i-ep-warning /></el-icon>
      <span style="margin-left: 8px; font-size: 20px; font-weight: bold;">日志管理</span>
    </div>
         <div class="toolbar">
       <el-input 
         v-model="logSearch" 
         placeholder="请输入用户名/操作" 
         style="width: 240px; margin-right: 16px;" 
         clearable 
         @input="handleSearchInput"
       />
       <el-button type="primary" @click="handleLogSearch">搜索</el-button>
       <el-button type="success" @click="exportLogs" style="margin-left: 16px;">导出日志</el-button>
       <el-button type="warning" @click="cleanLogs" style="margin-left: 16px;">清理日志</el-button>
       <el-button type="info" @click="fetchLogs" style="margin-left: 16px;" :loading="logLoading">刷新</el-button>
     </div>
    <el-table :data="pagedLogs" style="width: 100%; margin-top: 16px;" v-loading="logLoading">
      <el-table-column prop="username" label="用户名" />
      <el-table-column label="级别" width="100">
        <template #default="{ row }">
          <el-tag 
            :type="getLogLevelType(row.level)" 
            size="small"
            effect="dark"
          >
            {{ getLogLevelText(row.level) }}
          </el-tag>
        </template>
      </el-table-column>
             <el-table-column prop="action" label="操作" />
       <el-table-column prop="description" label="描述" show-overflow-tooltip />
       <el-table-column prop="ipAddress" label="IP地址" width="120" />
       <el-table-column label="创建时间" width="180">
         <template #default="{ row }">
           {{ formatDateTime(row.createdAt) }}
         </template>
       </el-table-column>
      <el-table-column label="操作" width="120">
        <template #default="{ row }">
          <el-button size="small" @click="viewLogDetail(row)">查看详情</el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination background layout="total, prev, pager, next, jumper" :total="Array.isArray(filteredLogs) ? filteredLogs.length : 0" :page-size="logPageSize" :current-page="logCurrentPage" @current-change="handleLogPageChange" style="margin-top: 16px; text-align: right;" />
    
    <!-- 日志详情弹窗 -->
    <el-dialog title="日志详情" v-model="logDetailVisible" width="600px">
      <el-descriptions :column="1" border>
        <el-descriptions-item label="用户名">{{ selectedLog?.username }}</el-descriptions-item>
        <el-descriptions-item label="级别">
          <el-tag 
            :type="getLogLevelType(selectedLog?.level)" 
            size="small"
            effect="dark"
          >
            {{ getLogLevelText(selectedLog?.level) }}
          </el-tag>
        </el-descriptions-item>
        <el-descriptions-item label="操作">{{ selectedLog?.action }}</el-descriptions-item>
        <el-descriptions-item label="描述">{{ selectedLog?.description }}</el-descriptions-item>
                 <el-descriptions-item label="IP地址">{{ selectedLog?.ipAddress }}</el-descriptions-item>
         <el-descriptions-item label="创建时间">{{ formatDateTime(selectedLog?.createdAt) }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <el-button @click="logDetailVisible = false">关闭</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { getApiUrl } from '../config/api.js'

// 日志管理数据
const logs = ref([])
const logSearch = ref('')
const logPageSize = ref(10)
const logCurrentPage = ref(1)
const logLoading = ref(false)
const logDetailVisible = ref(false)
const selectedLog = ref(null)

const filteredLogs = computed(() => {
  if (!logSearch.value) return Array.isArray(logs.value) ? logs.value : []
  const keyword = logSearch.value.toLowerCase()
  const logsArray = Array.isArray(logs.value) ? logs.value : []
  return logsArray.filter(log => 
    log.username?.toLowerCase().includes(keyword) ||
    log.action?.toLowerCase().includes(keyword) ||
    log.description?.toLowerCase().includes(keyword)
  )
})

const pagedLogs = computed(() => {
  const start = (logCurrentPage.value - 1) * logPageSize.value
  const filtered = Array.isArray(filteredLogs.value) ? filteredLogs.value : []
  return filtered.slice(start, start + logPageSize.value)
})

const todayLogsCount = computed(() => {
  const today = new Date()
  const logsArray = Array.isArray(logs.value) ? logs.value : []
  return logsArray.filter(log => {
    const logDate = new Date(log.createdAt)
    return logDate.toDateString() === today.toDateString()
  }).length
})

const weekLogsCount = computed(() => {
  const now = new Date()
  const weekStart = new Date(now.getFullYear(), now.getMonth(), now.getDate() - now.getDay())
  const logsArray = Array.isArray(logs.value) ? logs.value : []
  return logsArray.filter(log => {
    const logDate = new Date(log.createdAt)
    return logDate >= weekStart
  }).length
})

const monthLogsCount = computed(() => {
  const now = new Date()
  const logsArray = Array.isArray(logs.value) ? logs.value : []
  return logsArray.filter(log => {
    const logDate = new Date(log.createdAt)
    return logDate.getMonth() === now.getMonth() && logDate.getFullYear() === now.getFullYear()
  }).length
})

// 获取日志数据
async function fetchLogs() {
  logLoading.value = true
  try {
    const params = {
      page: logCurrentPage.value,
      pageSize: logPageSize.value
    }

    if (logSearch.value) {
      params.username = logSearch.value
      params.action = logSearch.value
    }

    const res = await axios.get(getApiUrl('/log/list'), { params })
    
    if (res.data) {
      logs.value = res.data.logs || []
      // total.value = res.data.total || 0 // This line was removed from the new_code, so it's removed here.
    }
  } catch (error) {
    console.error('获取日志失败:', error)
    ElMessage.error('获取日志失败: ' + (error.response?.data || error.message))
  } finally {
    logLoading.value = false
  }
}

// 获取统计信息
async function fetchStatistics() {
  try {
    const res = await axios.get(getApiUrl('/log/statistics'))
    if (res.data) {
      // statistics.value = res.data // This line was removed from the new_code, so it's removed here.
    }
  } catch (error) {
    console.error('获取统计信息失败:', error)
  }
}

// 导出日志
async function exportLogs() {
  try {
    const params = {}
    if (logSearch.value) {
      params.username = logSearch.value
      params.action = logSearch.value
    }

    const res = await axios.get(getApiUrl('/log/export'), { 
      params,
      responseType: 'blob'
    })

    if (res.status === 200) {
      const url = window.URL.createObjectURL(new Blob([res.data]))
      const link = document.createElement('a')
      link.href = url
      link.setAttribute('download', `logs_${new Date().toISOString().split('T')[0]}.csv`)
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      window.URL.revokeObjectURL(url)
      ElMessage.success('日志导出成功')
    }
  } catch (error) {
    console.error('导出日志失败:', error)
    ElMessage.error('导出日志失败: ' + (error.response?.data || error.message))
  }
}

// 清理日志
async function cleanLogs() {
  try {
    await ElMessageBox.confirm('确定要清理30天前的日志吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    const beforeDate = new Date()
    beforeDate.setDate(beforeDate.getDate() - 30)

    const res = await axios.delete(getApiUrl('/log/clean'), {
      params: { beforeDate: beforeDate.toISOString() }
    })

    if (res.status === 200) {
      ElMessage.success('日志清理成功')
      fetchLogs()
      // fetchStatistics() // This line was removed from the new_code, so it's removed here.
    }
  } catch (error) {
    if (error.message !== 'cancel') {
      console.error('清理日志失败:', error)
      ElMessage.error('清理日志失败: ' + (error.response?.data || error.message))
    }
  }
}

// 生成模拟日志数据
function generateMockLogs() {
  const mockLogs = []
  const actions = ['登录', '登出', '创建用户', '删除用户', '修改权限', '上传文件', '下载文件']
  const levels = ['INFO', 'WARNING', 'ERROR', 'DEBUG']
  const usernames = ['admin', 'user1', 'user2', 'manager']
  
  for (let i = 0; i < 50; i++) {
    const randomDate = new Date()
    randomDate.setDate(randomDate.getDate() - Math.floor(Math.random() * 30))
    
    mockLogs.push({
      id: i + 1,
      username: usernames[Math.floor(Math.random() * usernames.length)],
      action: actions[Math.floor(Math.random() * actions.length)],
      description: `用户执行了${actions[Math.floor(Math.random() * actions.length)]}操作`,
      level: levels[Math.floor(Math.random() * levels.length)],
      ipAddress: `192.168.1.${Math.floor(Math.random() * 255)}`,
      createdAt: randomDate.toISOString()
    })
  }
  
  return mockLogs.sort((a, b) => new Date(b.createdAt) - new Date(a.createdAt))
}

// 获取日志级别类型
function getLogLevelType(level) {
  const typeMap = {
    'INFO': 'success',
    'WARNING': 'warning',
    'ERROR': 'danger',
    'DEBUG': 'info'
  }
  return typeMap[level] || 'info'
}

// 获取日志级别文本
function getLogLevelText(level) {
  const textMap = {
    'INFO': '信息',
    'WARNING': '警告',
    'ERROR': '错误',
    'DEBUG': '调试'
  }
  return textMap[level] || level
}

function handleLogSearch() {
  logCurrentPage.value = 1
  console.log('搜索关键词:', logSearch.value)
}

// 监听搜索输入变化，实现实时搜索
function handleSearchInput() {
  logCurrentPage.value = 1
}

function handleLogPageChange(page) {
  logCurrentPage.value = page
}

function viewLogDetail(log) {
  selectedLog.value = log
  logDetailVisible.value = true
}

// 格式化日期时间
function formatDateTime(dateTimeStr) {
  if (!dateTimeStr) return ''
  try {
    const date = new Date(dateTimeStr)
    return date.toLocaleString('zh-CN', {
      year: 'numeric',
      month: '2-digit',
      day: '2-digit',
      hour: '2-digit',
      minute: '2-digit',
      second: '2-digit'
    })
  } catch (e) {
    return dateTimeStr
  }
}

// 生成CSV内容
function generateCSVContent() {
  const headers = ['用户名', '操作', '级别', '描述', 'IP地址', '创建时间']
  const csvRows = [headers.join(',')]
  
  const logsArray = Array.isArray(logs.value) ? logs.value : []
  logsArray.forEach(log => {
    const row = [
      log.username || '',
      log.action || '',
      log.level || '',
      log.description || '',
      log.ipAddress || '',
      formatDateTime(log.createdAt) || ''
    ].map(field => `"${field}"`).join(',')
    csvRows.push(row)
  })
  
  return csvRows.join('\n')
}

// 组件挂载时获取数据
onMounted(() => {
  console.log('LogManagement 组件已挂载，开始获取日志数据...')
  fetchLogs()
})
</script>

<style scoped>
.sys-section-bg {
  padding: 24px;
  background: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.04);
}

.sys-stat-row {
  margin-bottom: 24px;
}

.sys-stat-card {
  border-radius: 8px;
  transition: all 0.3s;
}

.sys-stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 16px;
}

.stat-info {
  margin-left: 16px;
}

.stat-title {
  font-size: 14px;
  color: #666;
  margin-bottom: 4px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #333;
}

.page-title {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  color: #333;
}

.toolbar {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
</style> 